package com.rr.sc.init;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.rr.sc.bo.CategoryBo;
import com.rr.sc.bo.UserBo;
import com.rr.sc.model.Category;
import com.rr.sc.model.User;

@Component
public class ApplicationSetup implements InitializingBean {
	private UserBo userBo;
	private CategoryBo categoryBo;

	@Autowired
	private ApplicationSetup(UserBo userBo, CategoryBo categoryBo) {
		this.userBo = userBo;
		this.categoryBo = categoryBo;
	}

	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

		List<Category> genericCategories = categoryBo.getByUserId(null, false);
		if (CollectionUtils.isEmpty(genericCategories)) {
			Category foodCategory = new Category();
			foodCategory.setName("Food");
			foodCategory.setDescription("Food costs");
			categoryBo.saveOrUpdate(foodCategory);

			Category carCategory = new Category();
			carCategory.setName("Car");
			carCategory.setDescription("Car costs");
			categoryBo.saveOrUpdate(carCategory);

			Category fuelCategory = new Category();
			fuelCategory.setName("Fuel");
			fuelCategory.setDescription("Fuel costs");
			fuelCategory.setParentCategory(carCategory);
			categoryBo.saveOrUpdate(fuelCategory);

			Category insuranceCategory = new Category();
			insuranceCategory.setName("Insurance");
			insuranceCategory.setDescription("Insurance costs");
			insuranceCategory.setParentCategory(carCategory);
			categoryBo.saveOrUpdate(insuranceCategory);

			Category houseCategory = new Category();
			houseCategory.setName("House");
			houseCategory.setDescription("House costs");
			categoryBo.saveOrUpdate(houseCategory);

			Category rentCategory = new Category();
			rentCategory.setName("Rent");
			rentCategory.setDescription("Rent costs");
			rentCategory.setParentCategory(houseCategory);
			categoryBo.saveOrUpdate(rentCategory);

			Category maintenanceCategory = new Category();
			maintenanceCategory.setName("Maintenance");
			maintenanceCategory.setDescription("Maintenance costs");
			maintenanceCategory.setParentCategory(houseCategory);
			categoryBo.saveOrUpdate(maintenanceCategory);

			Category otherCategory = new Category();
			otherCategory.setName("Others");
			otherCategory.setDescription("Other costs");
			categoryBo.saveOrUpdate(otherCategory);
		}

		User admin = userBo.get("admin");
		if (admin == null) {
			admin = new User();
			admin.setUsername("admin");
			admin.setPassword("admin");
			userBo.saveOrUpdate(admin);
		}
	}
}
